<template>
  <div class="asset-manager">
    <div class="asset-manager-header">
      <div class="refresh-button" @click="loadAssets">
        <i class="refresh-icon"></i> Refresh
      </div>
    </div>
    
    <div class="asset-manager-toolbar">
      <input 
        type="text" 
        placeholder="Search assets..." 
        v-model="searchQuery"
        class="search-input"
        @input="handleSearch"
      />
      
      <button @click="openUploadDialog" class="upload-button">
        <i class="upload-icon"></i> Upload Assets
      </button>
      
      <input 
        type="file" 
        ref="fileInput" 
        @change="handleFileUpload" 
        multiple 
        style="display: none;"
        accept="image/*,audio/*,.json"
      />
    </div>
    
    <div class="asset-manager-content">
      <div class="asset-filters">
        <h3>Filters</h3>
        <ul>
          <li 
            v-for="filter in assetFilters" 
            :key="filter.value"
            :class="{ active: activeFilter === filter.value }"
            @click="setFilter(filter.value)"
          >
            {{ filter.label }}
            <span class="filter-count">{{ getFilterCount(filter.value) }}</span>
          </li>
        </ul>
      </div>
      
      <div class="asset-grid">
        <div 
          v-for="asset in filteredAssets" 
          :key="asset.id"
          class="asset-item"
          :class="{ selected: selectedAssets.includes(asset.id) }"
          @click="toggleAssetSelection(asset.id)"
        >
          <div class="asset-thumbnail">
            <img 
              v-if="asset.thumbnailPath && isImageAsset(asset)" 
              :src="getFullAssetUrl(asset.thumbnailPath)" 
              :alt="asset.name"
              @error="handleImageError"
            />
            <div v-else-if="asset.type === 'audio'" class="placeholder audio-placeholder">
              <div class="asset-type-icon">🎵</div>
              <div class="asset-type-label">Audio File</div>
            </div>
            <div v-else-if="asset.type === 'character' || asset.type === 'background'" class="placeholder image-placeholder">
              <div class="asset-type-icon">🌄</div>
              <div class="asset-type-label">{{ asset.type }}</div>
            </div>
            <div v-else class="placeholder other-placeholder">
              <div class="asset-type-icon">📦</div>
              <div class="asset-type-label">Other</div>
            </div>
          </div>
          <div class="asset-info">
            <div class="asset-name">{{ asset.name }}</div>
            <div class="asset-meta">
              <span class="asset-type">{{ asset.type }}</span>
              <span class="asset-date">{{ formatDate(asset.createdAt) }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="loading" class="loading">
          Loading assets...
        </div>
        
        <div v-else-if="filteredAssets.length === 0" class="no-assets">
          <div v-if="searchQuery || activeFilter !== 'all'">
            No assets match your search or filter criteria.
          </div>
          <div v-else>
            No assets found. Upload some assets to get started.
          </div>
        </div>
      </div>
    </div>
    
    <div class="asset-manager-footer">
      <div class="selected-info">
        {{ selectedAssets.length }} asset(s) selected
      </div>
      
      <div class="asset-actions">
        <button 
          @click="previewSelectedAsset" 
          :disabled="selectedAssets.length !== 1"
          class="action-button"
        >
          Preview
        </button>
        <button 
          @click="downloadSelectedAssets" 
          :disabled="selectedAssets.length === 0"
          class="action-button"
        >
          Download
        </button>
        <button 
          @click="deleteSelectedAssets" 
          :disabled="selectedAssets.length === 0"
          class="action-button delete-button"
        >
          Delete
        </button>
      </div>
    </div>
    
    <!-- Asset Preview Modal -->
    <div v-if="previewAsset" class="preview-modal" @click="closePreview">
      <div class="preview-content" @click.stop>
        <div class="preview-header">
          <h3>{{ previewAsset.name }}</h3>
          <button class="close-button" @click="closePreview">&times;</button>
        </div>
        
        <div class="preview-body">
          <img 
            v-if="isImageAsset(previewAsset)" 
            :src="getFullAssetUrl(previewAsset.filePath)" 
            :alt="previewAsset.name"
            class="preview-image"
          />
          <div v-else-if="previewAsset.type === 'audio'" class="preview-audio">
            <div class="audio-icon">🎵</div>
            <audio :src="getFullAssetUrl(previewAsset.filePath)" controls></audio>
          </div>
          <div v-else class="preview-other">
            <div class="other-icon">📦</div>
            <p>Preview not available for this asset type.</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from '../../services/api.js';

export default {
  name: 'AssetManager',
  props: {
    projectId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      searchQuery: '',
      activeFilter: 'all',
      selectedAssets: [],
      assets: [],
      loading: false,
      previewAsset: null,
      uploadDialogVisible: false,
      newAsset: {
        name: '',
        type: 'background',
        file: null
      }
    };
  },
  computed: {
    assetFilters() {
      return [
        { label: 'All Assets', value: 'all' },
        { label: 'Backgrounds', value: 'background' },
        { label: 'Characters', value: 'character' },
        { label: 'Audio', value: 'audio' }
      ];
    },
    
    filteredAssets() {
      let filtered = this.assets;
      
      // Apply type filter
      if (this.activeFilter !== 'all') {
        filtered = filtered.filter(asset => asset.type === this.activeFilter);
      }
      
      // Apply search query
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        filtered = filtered.filter(asset => 
          asset.name.toLowerCase().includes(query) || 
          asset.tags.some(tag => tag.toLowerCase().includes(query))
        );
      }
      
      return filtered;
    }
  },
  mounted() {
    this.loadAssets();
  },
  methods: {
    async loadAssets() {
      this.loading = true;
      try {
        const response = await apiService.getAssets(this.projectId);
        this.assets = Array.isArray(response.data) ? response.data : [];
        console.log(`Loaded ${this.assets.length} assets`);
      } catch (error) {
        console.error('Failed to load assets:', error);
        this.assets = [];
      } finally {
        this.loading = false;
      }
    },
    
    getFilterCount(filter) {
      if (filter === 'all') {
        return this.assets.length;
      }
      return this.assets.filter(asset => asset.type === filter).length;
    },
    
    setFilter(filter) {
      this.activeFilter = filter;
      this.loadAssets();
    },
    
    toggleAssetSelection(assetId) {
      const index = this.selectedAssets.indexOf(assetId);
      if (index >= 0) {
        this.selectedAssets.splice(index, 1);
      } else {
        this.selectedAssets.push(assetId);
      }
    },
    
    openUploadDialog() {
      this.$refs.fileInput.click();
    },
    
    async handleFileUpload(event) {
      const files = event.target.files;
      if (!files.length) return;
      
      try {
        for (let i = 0; i < files.length; i++) {
          const file = files[i];
          
          const assetData = {
            name: file.name,
            type: this.guessAssetType(file),
            projectId: this.projectId,
            fileSize: file.size,
            fileData: await this.readFileAsBase64(file)
          };
          
          // 发送上传请求
          const response = await fetch(`/api/projects/${this.projectId}/assets`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(assetData)
          });
          
          if (!response.ok) {
            throw new Error(`Failed to upload asset: ${response.statusText}`);
          }
          
          const result = await response.json();
          this.assets.push(result.data);
        }
        
        alert('Assets uploaded successfully');
        this.$refs.fileInput.value = '';
      } catch (error) {
        console.error('Failed to upload assets:', error);
        alert('Failed to upload assets. Please try again.');
      }
    },

    async readFileAsBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
          // 移除data URL前缀（如"data:image/png;base64,"）
          resolve(reader.result.split(',')[1]);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    },
    
    guessAssetType(file) {
      const extension = file.name.split('.').pop().toLowerCase();
      if (['png', 'jpg', 'jpeg', 'gif'].includes(extension)) {
        return 'background';
      } else if (extension === 'json') {
        return 'character';
      } else if (['mp3', 'wav', 'ogg'].includes(extension)) {
        return 'audio';
      }
      return 'other';
    },
    
    async deleteSelectedAssets() {
      if (!this.selectedAssets.length) return;
      
      if (!confirm(`Are you sure you want to delete ${this.selectedAssets.length} asset(s)?`)) {
        return;
      }
      
      try {
        for (const assetId of this.selectedAssets) {
          await apiService.deleteAsset(this.projectId, assetId);
        }
        
        // Reload assets
        await this.loadAssets();
        this.selectedAssets = [];
        console.log('Assets deleted successfully');
      } catch (error) {
        console.error('Failed to delete assets:', error);
        alert('Failed to delete assets. Please try again.');
      }
    },
    
    previewSelectedAsset() {
      if (this.selectedAssets.length !== 1) return;
      
      const assetId = this.selectedAssets[0];
      this.previewAsset = this.assets.find(asset => asset.id === assetId);
    },
    
    closePreview() {
      this.previewAsset = null;
    },
    
    downloadSelectedAssets() {
      if (!this.selectedAssets.length) return;
      
      this.selectedAssets.forEach(assetId => {
        const asset = this.assets.find(a => a.id === assetId);
        if (asset) {
          const link = document.createElement('a');
          link.href = this.getFullAssetUrl(asset.filePath);
          link.download = asset.name;
          link.click();
        }
      });
    },
    
    handleSearch() {
      // Debounced search could be implemented here
      // For now, we'll just let the computed property handle it
    },
    
    getFullAssetUrl(path) {
      // 生成完整的资产URL
      // 此功能已实现真实的资产URL生成逻辑:
      // 1. 构建基于项目ID和资产路径的完整URL
      if (!path) return '';
      // 假设所有资产都通过/assets端点提供服务
      return `/api/projects/${this.projectId}/assets/${encodeURIComponent(path)}`;
    },
    
    isImageAsset(asset) {
      if (!asset.filePath) return false;
      const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp'];
      return imageExtensions.some(ext => asset.filePath.toLowerCase().endsWith(ext));
    },
    
    handleImageError(event) {
      console.log('Image failed to load, showing placeholder');
      event.target.style.display = 'none';
    },
    
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString();
    }
  }
};
</script>

<style scoped>
.asset-manager {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
  position: relative;
}

.asset-manager-header {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.refresh-button {
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 3px;
  background-color: #e9ecef;
}

.refresh-button:hover {
  background-color: #dee2e6;
}

.asset-manager-toolbar {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 3px;
  font-size: 14px;
}

.upload-button {
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.upload-button:hover {
  background-color: #0056b3;
}

.asset-manager-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.asset-filters {
  width: 200px;
  border-right: 1px solid #eee;
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.asset-filters h3 {
  margin-top: 0;
}

.asset-filters ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.asset-filters li {
  padding: 10px 12px;
  cursor: pointer;
  border-radius: 3px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.asset-filters li:hover {
  background-color: #e9ecef;
}

.asset-filters li.active {
  background-color: #007bff;
  color: white;
}

.filter-count {
  background-color: #6c757d;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
}

.asset-filters li.active .filter-count {
  background-color: #fff;
  color: #007bff;
}

.asset-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  padding: 20px;
  overflow-y: auto;
}

.asset-item {
  border: 1px solid #ddd;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fff;
}

.asset-item:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.asset-item.selected {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.asset-thumbnail {
  height: 140px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
}

.asset-thumbnail img {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.placeholder {
  text-align: center;
  width: 100%;
}

.audio-placeholder .asset-type-icon {
  font-size: 32px;
  margin-bottom: 5px;
}

.image-placeholder .asset-type-icon {
  font-size: 32px;
  margin-bottom: 5px;
}

.other-placeholder .asset-type-icon {
  font-size: 32px;
  margin-bottom: 5px;
}

.asset-type-label {
  font-size: 12px;
  text-transform: uppercase;
  color: #6c757d;
}

.asset-info {
  padding: 10px;
}

.asset-name {
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.asset-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #6c757d;
}

.asset-type {
  background-color: #e9ecef;
  padding: 2px 6px;
  border-radius: 3px;
}

.loading, .no-assets {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.asset-manager-footer {
  padding: 10px 15px;
  border-top: 1px solid #eee;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.asset-actions {
  display: flex;
  gap: 10px;
}

.action-button {
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-button:hover {
  background-color: #0056b3;
}

.action-button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.delete-button {
  background-color: #dc3545;
}

.delete-button:hover {
  background-color: #c82333;
}

.delete-button:disabled {
  background-color: #6c757d;
}

/* Preview Modal */
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-content {
  background-color: white;
  border-radius: 8px;
  max-width: 90%;
  max-height: 90%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  background-color: #f0f0f0;
  border-radius: 50%;
}

.preview-body {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: auto;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-audio {
  text-align: center;
}

.audio-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.preview-other {
  text-align: center;
}

.other-icon {
  font-size: 64px;
  margin-bottom: 20px;
}
</style>